﻿#include "databasewig.h"
#include "ui_databasewig.h"
#include "utilscommon.h"
#include "randomname.h"
#include "gbk.h"

//参考资料：https://blog.csdn.net/linan_pin/article/details/70158259

DataBaseWig::DataBaseWig(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DataBaseWig)
{
    ui->setupUi(this);
    stuDao.initTable();

    updateStuTable();
    qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
    on_randmStuBtn_clicked();
}

void DataBaseWig::updateStuTable()
{
    QList<StudentData> list;
    stuDao.querryAll(list);

    ui->stuTable->clear();

    int rowCount = list.length();
    ui->stuTable->setRowCount(rowCount);
    for(int i=0; i<rowCount; i++){
        ui->stuTable->setItem(i, 0, new QTableWidgetItem(list.at(i).num));
        ui->stuTable->setItem(i, 1, new QTableWidgetItem(list.at(i).name));
        ui->stuTable->setItem(i, 2, new QTableWidgetItem(list.at(i).sex? a2w("男"):a2w("女")));
        ui->stuTable->setItem(i, 3, new QTableWidgetItem(QString::number(list.at(i).age)));
    }
}

void DataBaseWig::on_addStuBtn_clicked()
{
    StudentData stu;
    stu.num = ui->addStuTable->item(0,0)->text();
    stu.name = ui->addStuTable->item(0,1)->text();
    stu.sex = ui->addStuTable->item(0,2)->text()==a2w("男") ? 1:0;
    stu.age = ui->addStuTable->item(0,3)->text().toInt();

    stuDao.insert(stu);

    updateStuTable();
}

void DataBaseWig::on_randmStuBtn_clicked()
{
    ui->addStuTable->item(0,0)->setText(utilscommon::getRandomNum(10));
    ui->addStuTable->item(0,1)->setText(a2w(RandomName().getName()));
    ui->addStuTable->item(0,2)->setText(utilscommon::getRandomNum(0,2)? a2w("男"):a2w("女"));
    ui->addStuTable->item(0,3)->setText(QString().number(utilscommon::getRandomNum(10,60)));
}

void DataBaseWig::on_delStuBtn_clicked()
{
    stuDao.delById(ui->delStuTable->item(0,0)->text());
    updateStuTable();
}

void DataBaseWig::on_stuTable_clicked(const QModelIndex &index)
{
    int row = index.row();
    QString num = ui->stuTable->item(row,0)->text();
    QString name = ui->stuTable->item(row,1)->text();
    QString sex = ui->stuTable->item(row,2)->text();
    QString age = ui->stuTable->item(row,3)->text();

    ui->delStuTable->item(0,0)->setText(num);
    ui->delStuTable->item(0,1)->setText(name);
    ui->delStuTable->item(0,2)->setText(sex);
    ui->delStuTable->item(0,3)->setText(age);

    ui->modStuTable->item(0,0)->setText(num);
    ui->modStuTable->item(0,1)->setText(name);
    ui->modStuTable->item(0,2)->setText(sex);
    ui->modStuTable->item(0,3)->setText(age);
}
